package com.opensource.afuluo.runtime;

import com.google.common.base.Joiner;
import com.google.common.collect.Maps;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;

import java.util.Map;

public class PublishedService {

    private static ApplicationContext applicationContext;

    private static final Map<String, Object> SERVICE_CACHE = Maps.newConcurrentMap();

    /**
     * 获取发布服务实例
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getInstance(Class<T> clazz) {
        return getInstance(clazz, "");
    }

    /**
     * 获取发布服务实例
     *
     * @param clazz
     * @param unique 自定义服务名
     * @param <T>
     * @return
     */
    public static <T> T getInstance(Class<T> clazz, String unique) {
        String prefix = Joiner.on("#").join(
                clazz.getCanonicalName(),
                unique
        );
        Object instance = SERVICE_CACHE.get(prefix);
        if (null == instance) {
            try {
                if (!StringUtils.isEmpty(unique)) {
                    instance = applicationContext.getBean(unique, clazz.getClass());
                }
                if (null == instance) {
                    instance = applicationContext.getBean(clazz.getClass());
                }
                SERVICE_CACHE.putIfAbsent(prefix, instance);
            } catch (Exception e) {
                return null;
            }
        }
        return (T) instance;
    }

    public static void setApplicationContext(ApplicationContext applicationContext) {
        PublishedService.applicationContext = applicationContext;
    }
}
